import {
  defaultValue,
  Viewer,
  defined,
  ScreenSpaceEventType,
  Camera,
  Rectangle
} from 'cesium';
const MapViewer = function (container, options) {
  options = defaultValue(options, {});
  options.shouldAnimate = defaultValue(options.shouldAnimate, false);
  options.baseLayerPicker = defaultValue(options.baseLayerPicker, false);
  options.sceneModePicker = defaultValue(options.sceneModePicker, false);
  options.navigationHelpButton = defaultValue(options.navigationHelpButton, false);
  options.homeButton = defaultValue(options.homeButton, false);
  options.geocoder = defaultValue(options.geocoder, false);
  options.infoBox = defaultValue(options.infoBox, false);
  options.selectionIndicator = defaultValue(options.selectionIndicator, false);
  options.animation = defaultValue(options.animation, false);
  options.timeline = defaultValue(options.timeline, false);
  options.fullscreenButton = defaultValue(options.fullscreenButton, false);
  options.vrButton = defaultValue(options.vrButton, false);
  Viewer.apply(this, [container, options]);

  Camera.DEFAULT_VIEW_RECTANGLE = Rectangle.fromDegrees(80, 22, 130, 50);
  this._cesiumWidget._creditContainer.style.display = 'none';
}

MapViewer.prototype = Object.create(Viewer.prototype);

MapViewer.prototype.globalScreenSpaceInputListener = function (options) {
  let scene = this.scene;

  // 全局事件监听
  this.globalScreenSpaceInputListener = defaultValue(
    options,
    Object.freeze({})
  );

  let globalScreenSpaceInputListener = this.globalScreenSpaceInputListener;

  //是否开启鼠标左键事件监听，默认为false；
  globalScreenSpaceInputListener.enableLeftClick = defaultValue(
    options.enableLeftClick,
    false
  );

  let enableLeftClick = globalScreenSpaceInputListener.enableLeftClick;

  //当前状态下的拾取信息
  this._fixedFramePickInfo = undefined;

  let fixedFramePickInfo = this._fixedFramePickInfo;

  let pickId;
  let pickObject;

  function applyListenerByName(object, methodName, movement) {
    //如果该对象无法被监听，则返回
    if (!defined(object.clickCommand) || !object.clickCommand.enabledListener) {
      return;
    }

    let listeners = object.clickCommand[methodName];

    let canvasCoordinates = movement.position;

    for (let i = 0, len = listeners.length; i < len; i++) {
      listeners[i](object, {
        //cartesian: scene.pickPosition(canvasCoordinates),
        canvasCoordinates: canvasCoordinates,
      });
    }
  }

  const applyLeftClick = function (movement) {
    if (!enableLeftClick) {
      return;
    }
    //获取当前帧的拾取信息
    fixedFramePickInfo = scene.pick(movement.position, 4, 4);
    //如果未拾取，则返回
    if (!defined(fixedFramePickInfo)) {
      return;
    }
    pickId = fixedFramePickInfo.id;
    pickObject = defined(pickId) ? pickId : fixedFramePickInfo.primitive;
    applyListenerByName(pickObject, 'leftClickListeners', movement);
  }

  this.cesiumWidget.screenSpaceEventHandler.setInputAction(
    applyLeftClick,
    ScreenSpaceEventType.LEFT_CLICK
  );
};

export default MapViewer;